// MIME类型到文件后缀的映射
const MIME_TO_EXTENSION = {
  'application/pdf': 'pdf',
  'application/zip': 'zip',
  'application/vnd.ms-excel': 'xls',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
  'text/csv': 'csv',
  'image/png': 'png',
  'image/jpeg': 'jpeg',
  'text/plain': 'txt',
};

export const downloadFile = (file, fileName) => {
  const url = window.URL.createObjectURL(new Blob([file]));
  // 自动添加文件后缀
  let finalName = fileName;
  if (file.type) {
    const ext = MIME_TO_EXTENSION[file.type];
    if (ext && !fileName.includes('.')) {
      // 如果文件名没有后缀才添加
      finalName = `${fileName}.${ext}`;
    }
  }
  downloadUrl(url, finalName);
  // 释放内存
  URL.revokeObjectURL(url);
};

export const downloadUrl = (url, fileName) => {
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
